package com.wwm.makerandroid.makerandroid.View.Fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lipiao.makerandroid.R;

import com.wwm.makerandroid.makerandroid.Bean.RespondBean.MessageBean;
import com.wwm.makerandroid.makerandroid.Bean.RespondBean.RecordBean;
import com.wwm.makerandroid.makerandroid.Bean.RespondBean.TempBean;
import com.wwm.makerandroid.makerandroid.Bean.RespondBean.TopArticleBean;
import com.wwm.makerandroid.makerandroid.Bean.RespondBean.UserDto;
import com.wwm.makerandroid.makerandroid.Bean.ViewBean.ApplyBean;
import com.wwm.makerandroid.makerandroid.Utils.DateUtil;
import com.wwm.makerandroid.makerandroid.Utils.HttpUtil;
import com.wwm.makerandroid.makerandroid.Utils.MyBeanUtils;
import com.wwm.makerandroid.makerandroid.View.Adapter.ApplyRecordAdapter;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

//原始的四个碎片自带缓存 无需懒加载 也不会重复加载数据
public class RecordFragment extends Fragment {

    static String userNumber;//账号
    Context mainActivity;
    String TAG = "MainFragment";
    View rootView;

    //碎片中使用butterknife略有不同
    private Unbinder unbinder;
    Button btUpdate;
    View applyView;
    //上一个未通过请假申请的数据
    ApplyBean lastRefuseApply = new ApplyBean();
    RadioGroup vehicleRG;
    private List recordList;
    private List<TopArticleBean.DataBean> topDataBeanList;
    AlertDialog alertDialog;//模拟加载数据

    //top article
    static ApplyRecordAdapter topArticleAdapter;
//    static List<ArticleBean> mList = new ArrayList<>();

    @SuppressLint("NonConstantResourceId")
    @BindView(R.id.rv_top_article)
    RecyclerView mRecyclerView;


    public RecordFragment() {
        // Required empty public constructor
    }

    public static RecordFragment newInstance(String username) {
        RecordFragment fragment = new RecordFragment();
        Bundle bundle = new Bundle();
        bundle.putString("userNumber", username);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mainActivity = getContext();
        rootView = inflater.inflate(R.layout.fragment_records, container, false);
        //返回一个Unbinder值（进行解绑），注意这里的this不能使用getActivity()
        unbinder = ButterKnife.bind(this, rootView);
        assert getArguments() != null;//判空处理
        userNumber = getArguments().getString("userNumber");//获取账号
        Log.d(TAG, "onCreateView: userNumber " + userNumber);
        initData();
        //点击按钮打开 修改页面
        btUpdate = rootView.findViewById(R.id.bt_update_pre);
        btUpdate.setOnClickListener(mOnClickListener);
        return rootView;
    }


    private void showApplyDialog(View view, Button button, String title) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        final AlertDialog dialog = builder.create();
        applyView = View.inflate(getContext(), R.layout.apply_card_item, null);
        dialog.setView(applyView);
        dialog.show();
        dialog.getWindow().setLayout(1400, 2500);
    }


    private void initData() {
        alertDialog = new AlertDialog.Builder(Objects.requireNonNull(getActivity()))
                .setMessage("获取请假记录中...")
                .setTitle("Maker——IoT").create();
        alertDialog.show();
        //LogUtil.d(TAG, "initData 验证是否重复加载碎片所需数据");

        //banner所需数据images titles
        //接口参数 无
        Call<ResponseBody> callBanner = HttpUtil.getUserService().getUserAllRecord(userNumber);
        //网络请求
        callBanner.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {

                    String strBack = response.body().string();
                    //处理数据
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(strBack);
                    Gson gson = new Gson();
                    RecordBean recordBean;

                    recordBean = gson.fromJson(jsonObject.toString(), RecordBean.class);
                    System.out.println(recordBean);
                    recordList = recordBean.getData();
                    initRecordView();

                    //获取完数据后UI操作
                    //主线程将alertDialog提示隐藏
                    Objects.requireNonNull(getActivity()).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            alertDialog.hide();
                        }
                    });
                } catch (JSONException e) {
                    System.out.println(e);
                    Log.d(TAG, "初始化项目数据成功");
                } catch (IOException e) {
                    System.out.println(e);
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.d(TAG, "初始化项目数据失败");
            }
        });
    }

    //初始化记录列表
    private void initRecordView() {
        //top rv
        mRecyclerView.setHasFixedSize(true);
        //平常的水平一个item布局的流
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        //设置预览信息

//初始化mList
//        initArticleBeanList();
//实例化MyAdapter并传入mList对象
        //这里原本是文章列表的构造器直接拿来复用了
        topArticleAdapter = new ApplyRecordAdapter(recordList);

//为RecyclerView对象mRecyclerView设置adapter
        mRecyclerView.setAdapter(topArticleAdapter);
    }










    //    打开未通过审批请假单的修改对话框
//这块和请假页面几乎一样单这个是打开对话框 请假页面是打开碎片页面 代码复用起来有点绕 直接再写一遍
    ApplyBean applyBean = new ApplyBean();
    //    涉及选择审批人这块都是屎
    HashMap<String, String> approverMap;
    String[] approverArray;
    List approvers;//用户可选请假的审批人
    String approver;//用户实际选择请假的审批人

    RadioGroup typeRG;
    Button startBt;
    Button endBt;
    EditText reasonText;
    Button destinationText;
    Spinner apprvoerSp;
    Button submitApplyBt;

    public void initApplyDialogView() {
        typeRG = applyView.findViewById(R.id.user_fragment_banner);
        vehicleRG=applyView.findViewById(R.id.rgv1);
        typeRG=applyView.findViewById(R.id.rg);

        reasonText = applyView.findViewById(R.id.et_reason);
        destinationText = applyView.findViewById(R.id.text_diqu);

        startBt = applyView.findViewById(R.id.bt_start);
        endBt = applyView.findViewById(R.id.bt_end);
//        approverBt = rootView.findViewById(R.id.);
        submitApplyBt = applyView.findViewById(R.id.bt_submitApply);
        apprvoerSp = applyView.findViewById(R.id.spinner);

        //添加点击监听
        startBt.setOnClickListener(timeOnClickListener);
        endBt.setOnClickListener(timeOnClickListener);

//        submitApplyBt.setOnClickListener(mOnClickListener);
        //调用接口查询 该用户有哪些审批人

        Call<MessageBean> call = HttpUtil.getUserService().getUserAllapprovers(userNumber);
        call.enqueue(new Callback<MessageBean>() {
            @Override
            public void onResponse(Call<MessageBean> call, Response<MessageBean> response) {
                approvers = (List) response.body().getData();
                //处理数据
                initSpinner();
            }

            @Override
            public void onFailure(Call<MessageBean> call, Throwable t) {

            }
        });


        submitApplyBt.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {

//验证数据
//todo 验证开始时间是否大于现在时间（虽然在打开选择开始时间对话框时已经设置过时间范围，
// 但是用户可以打开时间选择对话框后等很久再选开始时间 这样就会选择出比当前时间要早的错误请假开始时间）
// 是否比结束时间小

                applyBean.setUserNumber(userNumber);
                applyBean.setApproverId(approver);
                applyBean.setDestination(destinationText.getText().toString());
                RadioButton radioButton = (RadioButton) applyView.findViewById(typeRG.getCheckedRadioButtonId());
                String applyType = radioButton.getText().toString().substring(0, 1);
                String vehicle = radioButton.getText().toString().substring(0, 1);
                applyBean.setType(Integer.valueOf(applyType));
                applyBean.setVehicle(vehicle);
                applyBean.setOutDate(startBt.getText().toString() );
                applyBean.setExpectedReturnDate(endBt.getText().toString());
                applyBean.setReason(reasonText.getText().toString());

                submitApply(applyBean);
            }
        });
    }

    private View.OnClickListener mOnClickListener = v -> {
        //发送请求 获取上一个未通过审核的申请
        Call<ResponseBody> call = HttpUtil.getUserService().getLastRefuseApply(userNumber);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String strBack = response.body().string();
                    //处理数据
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(strBack);
                    Gson gson = new Gson();

                    lastRefuseApply = gson.fromJson(jsonObject.toString(), TempBean.class).getData();
                    if(lastRefuseApply==null){
                        return;
                    }
                    startBt.setText(lastRefuseApply.getOutDate());
                    endBt.setText(lastRefuseApply.getExpectedReturnDate());

                    destinationText.setText(lastRefuseApply.getDestination());
                    reasonText.setText(lastRefuseApply.getReason());
                    //应为是修改之前的申请要带上之前请假条的ID
                    applyBean.setId(lastRefuseApply.getId());
//       选项框回显选中有点复杂不想搞了
//                    typeRG.check(lastRefuseApply.getType());
                    //获取完数据后UI操作
                    //主线程将alertDialog提示隐藏
                    Objects.requireNonNull(getActivity()).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            alertDialog.hide();
                        }
                    });
                } catch (JSONException e) {
                    System.out.println(e);
                    Log.d(TAG, "获取上一个未通过审核的数据成功");
                } catch (IOException e) {
                    System.out.println(e);
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });

//       打开修改对话框
        showApplyDialog(v, btUpdate, "重写");
//     填写未修改前的数据
        initApplyDialogView();
    };


    private View.OnClickListener timeOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.bt_start://打开日期选择对话框

                    showDateDialog(v, startBt, "开始");
                    break;
                case R.id.bt_end://结束日期
                    showDateDialog(v, endBt, "结束");
                    break;
                default:
                    break;

            }
        }


    };


    //打开对话框 //todo 抽象成的方法
    private void showDateDialog(View view, Button button, String title) {

        AlertDialog.Builder builder = new AlertDialog.Builder(mainActivity);
        final AlertDialog dialog = builder.create();
        View dialogView = View.inflate(mainActivity, R.layout.bg_dialog_date, null);
        DatePicker datePicker = dialogView.findViewById(R.id.data_picker);
        TimePicker timePicker = dialogView.findViewById(R.id.time_picker);
        Button cancleBt = dialogView.findViewById(R.id.tv_data_dialog_cancel);
        Button doneBt = dialogView.findViewById(R.id.tv_data_dialog_done);
        TextView tv = dialogView.findViewById(R.id.tv_pickdatetime);

        timePicker.setIs24HourView(true);
        tv.setText("请选择" + title + "时间");

        //判断是选择开始时间还是结束时间  这一段可以不要
        if (button == startBt) {
            //选择开始时间 范围为 大于现在时间小于结束时间
            datePicker.setMinDate(System.currentTimeMillis());
            String endTime = null;
//            fixme 日期转换工具类问题
            try {
                endTime = DateUtil.timeStampDate2(endBt.getText().toString());
            } catch (Exception e) {
                System.out.println(endBt.getText().toString());
            }
            if (endTime != null) {
                datePicker.setMaxDate(Long.parseLong(endTime));
            }
        }


        cancleBt.setOnClickListener(view1 -> dialog.dismiss());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
        doneBt.setOnClickListener(dialogView1 -> {
//            button.setText(DatedatePicker.getDrawingTime());
            button.setText(datePicker.getYear() + "-" + getDatePickerTime(datePicker)+ " " + getTimePickerTime(timePicker));
            dialog.dismiss();
        });
        dialog.setView(dialogView);
        dialog.show();
    }


    private void submitApply(ApplyBean applyBean) {
        Gson gson = new Gson();

        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), gson.toJson(applyBean));
        Call<MessageBean> call = HttpUtil.getUserService().addapply(requestBody);
        call.enqueue(new Callback<MessageBean>() {
            @Override
            public void onResponse(Call<MessageBean> call, Response<MessageBean> response) {
//                Log.d(TAG, "onResponse: " + response.body().getMessage());
                Object strBack = null;
                try {
                    strBack = response.body().getData();

                    Map resmap = MyBeanUtils.getObjectToMap(strBack);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println(strBack);
                //获取到响应
                if (response.body().isSuccess()) {
                    Toast.makeText(mainActivity, "提交申请成功!", Toast.LENGTH_LONG).show();

                } else {
                    Toast.makeText(mainActivity, "提交失败!" + strBack, Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onFailure(Call<MessageBean> call, Throwable t) {
                Toast.makeText(mainActivity, t.getMessage(), Toast.LENGTH_LONG).show();
                Log.d("applyDialog", "onResponse: error");
                Log.d("applyDialog", t.getMessage());
            }
        });

    }

    //获取时间选择器的时间
    String getTimePickerTime(TimePicker timePicker) {
        //将小时和分钟都转为两位数 统一格式 方便传数据
        int hour = timePicker.getHour();
        String hourPrix="";
        String minutePrix="";
        if (hour < 10) {
            hourPrix="0";
        }
        int minute = timePicker.getMinute();
        if (minute < 10) {
            minutePrix = "0";
        }

        String res = hourPrix+hour + ":" +minutePrix+ minute;
        return res;
    }

    //获取日期选择器的日期
    String getDatePickerTime(DatePicker datePicker) {
        //将月份转天数为两位数 统一格式 方便传数据
        int month = datePicker.getMonth()+1;
        String monthPriex ="";
        String dayPriex ="";
        if (month < 10) {
            monthPriex="0";
        }
        int day = datePicker.getDayOfMonth();
        if (day < 10) {
            dayPriex="0";
        }

        String res = monthPriex+month + "-" + dayPriex+day;
        return res;
    }



    //获得当前用户的审批人员

    private void initSpinner() {
        approverMap = new HashMap<>();
        if (approvers != null) {
//            Gson gson = new Gsonbuilder.enableComplexMapKeySerialization().create();
            Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
            for (Object temp : approvers
            ) {

                String jsonString = gson.toJson(temp);
                UserDto userDto = gson.fromJson(jsonString, UserDto.class);

                approverMap.put(userDto.getName(), userDto.getId());
            }
        }
        approverArray = approverMap.keySet().toArray(new String[approverMap.size()]);
        //声明一个下拉列表的数组适配器
        ArrayAdapter<String> starAdapter = new ArrayAdapter<String>((Context) mainActivity, R.layout.item_select, approverArray);
        //设置下拉框的标题，不设置就没有难看的标题了
        apprvoerSp.setPrompt("请选择审批人");
        //设置下拉框的数组适配器
        apprvoerSp.setAdapter(starAdapter);
        //设置下拉框默认的显示第一项
        apprvoerSp.setSelection(0);
        //给下拉框设置选择监听器，一旦用户选中某一项，就触发监听器的onItemSelected方法
        apprvoerSp.setOnItemSelectedListener(new MySelectedListener());
    }

    class MySelectedListener implements AdapterView.OnItemSelectedListener {

        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
//            Toast.makeText(mainActivity, "您选择的是：" + approverArray[i], Toast.LENGTH_SHORT).show();
//            Toast.makeText(mainActivity, "您选择的是：" + approverMap.get(approverArray[i]), Toast.LENGTH_SHORT).show();
            approver = approverMap.get(approverArray[i]);
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    }

}
